<!--
 * @Author: zhayang
 * @LastEditors: zhuhaohua 250293786@qq.com
 * @Date: 2024-07-04 00:37:25
 * @LastEditTime: 2024-08-06 16:30:45
 * @Description: 单个拖拽
-->
<template>
  <div
    class="context relative"
    :style="`margin:-${data.h}px 0 0 -${data.w}px;width:${pw}px;height:${ph}px;`"
  >
    <template v-if="flag">
      <VueDraggableResizable
        v-if="data.src"
        :key="key"
        ref="dragRef"
        is-draggable
        is-resizable
        :parent-limitation="true"
        :w="data.w"
        :h="data.h"
        :y="data.y"
        :is-active="curActive"
        :x="data.x"
        aspect-ratio
        content-class="drag-item"
        @dragging="onDrag"
        @resizing="onResize"
        @resizestop="resizestop"
        @activated="onActivated()"
        @deactivated="onDeactivated"
      >
        <div
          style="overflow: hidden"
          class="w-100% h-100%"
        >
          <img
            draggable="false"
            class="w-100% h-100%"
            :src="data.src"
            :alt="data.src"
          />
        </div>
      </VueDraggableResizable>
    </template>
  </div>
</template>

<script>
import VueDraggableResizable from 'vue-drag-resize'
export default {
  name: 'Draggable',
  components: {
    VueDraggableResizable
  },
  props: {
    data: {
      type: Object,
      default: () => {
        return {
          x: 0,
          y: 0,
          w: 360,
          h: 640,
          src: ''
        }
      }
    }
  },
  data() {
    return {
      flag: false,
      pw: 360,
      ph: 640,
      key: 0,
      curActive: true // 当前激活下标
    }
  },
  watch: {
    data: {
      handler(val) {
        this.pw = 360 + val.w * 2
        this.ph = 640 + val.h * 2

        //
        // this.$refs.dragRef.activated()
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.flag = true
    })
  },
  methods: {
    onDrag({ top, left, width, height }) {
      // 移动
      this.$emit('updata', left, top)
    },
    onResize({ top, left, width, height }) {
      if (width > 0 && height > 0) {
        this.$emit('updata', left, top, width, height)
      }
    },
    resizestop() {
      this.key++
    },
    onDeactivated() {
      // 失去激活
      this.curActive = false
    },
    onActivated() {
      // 激活
      this.curActive = true
    }
  }
}
</script>

<style scoped lang="scss">
// @import 'vue-draggable-resizable/style.css';
img {
  user-select: none;
  pointer-events: none;
}
.vdr.active:before {
  outline: 1px dashed #04d1b8;
}
::v-deep .vdr-stick {
  background: #04d1b8;
  border: 1px solid #04d1b8;
  -webkit-box-shadow: 0 0 2px #04d1b8;
  box-shadow: 0 0 2px #04d1b8;
}
</style>
